package com.lkj.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.lkj.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.lkj.service.ServerServcie;
import com.lkj.utils.CommandUtil;
import com.lkj.utils.Ftputil;
import com.lkj.utils.PageUtil;
import com.lkj.utils.Param;

@Controller
@RequestMapping("/server")
public class ServerController {
	
	private static final int PAGESIZE = 5;
	
	@Autowired
	private ServerServcie serverService;
	
	/**
	 * 测试
	 * @param server
	 * @param model
	 * @return
	 */
	@RequestMapping("/insert")
	@ResponseBody
	public String insert(Server server,Model model){
		serverService.insert(server);
		//model.addAttribute(server);
		System.out.println(server.getServerip()+" "+server.getServername());
		
		return "true";
	}

	/**
	 * 登录
	 * @param user
	 * @return
	 */
    @RequestMapping(value = "/login",method=RequestMethod.POST)
    @ResponseBody
	public Map<String,Object> login(User user,HttpServletRequest request){
        Map<String,Object> map = serverService.login(user);
        if("success".equals(map.get("msg"))) request.getSession().setAttribute("user",map.get("user"));
		return map;
	}

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return "redirect:/login.jsp";
    }

	/**
	 * 主页
	 * @return
	 */
	@RequestMapping("/main")
	public String main(){
		return "new/registerManger";
	}
	
	/**
	 * 状态管理
	 * @return
	 */
	@RequestMapping("/statusManger")
	public String statusManger(){
		return "new/statusManger";
	}
	
	/**
	 * 
	 * 获取状态
	 * @param pageUtil
	 * @return
	 */
	@RequestMapping(value="/getStatus",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getStatus(PageUtil pageUtil){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("context", pageUtil.getContext());
		pageUtil.setPagesize(PAGESIZE);
		pageUtil.setTotalnum(serverService.getTotalRows(map));
		List<Status> list = serverService.getStatus(pageUtil);
		map.clear();
		map.put("list", list);
		map.put("pageUtil", pageUtil);
		return map;
	}
	
	
	@RequestMapping("/updateStatus")
	@ResponseBody
	public String updateStatus(Status status,Model model){
		serverService.updateStatus(status);
		return "1";
	}

    @RequestMapping("/updateFileServer")
    @ResponseBody
    public String updateFileServer(Server server,Model model){
        serverService.updateFileServer(server);
        return "1";
    }

    @RequestMapping("/updateScene")
    @ResponseBody
    public String updateScene(Scene scene,Model model){
        serverService.updateScene(scene);
        return "1";
    }


	
	/**
	 * 场景管理
	 * @return
	 */
	@RequestMapping("/sceneManger")
	public String sceneManger(){
		return "new/sceneManger";
	}
	
	@RequestMapping(value="/getScenes",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getScenes(PageUtil pageUtil){
		Map<String, Object> map = new HashMap<String, Object>();
		pageUtil.setPagesize(PAGESIZE);
		pageUtil.setTotalnum(serverService.getTotalRows_scene(pageUtil));
		List<Scene> list = serverService.getScenes(pageUtil);
		map.put("list", list);
		map.put("pageUtil", pageUtil);
		return map;
	}
	
	/**
	 * 
	 * 新建场景页
	 * @return
	 */
	@RequestMapping("/newScene")
	public String toAddScene(){
		return "new/newScene";
	}
	
	/**
	 * 获取所有神经网络
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getNervenets",method=RequestMethod.POST)
	@ResponseBody
	public Model getNervenets(Model model){
		List<Scene> list = serverService.getNervenets();
		return model.addAttribute("nervenets", list);
	}
	
	/**
	 * 
	 * 新建场景
	 * @param scene
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/addScene",method=RequestMethod.POST)
	@ResponseBody
	public Integer addScene(Scene scene,Model model){
		Integer id = serverService.addScene(scene);
		return id;
	}
	
	/**
	 * 文件服务器管理
	 * @return
	 */
	@RequestMapping("/fileServerManger")
	public String fileServerManger(Model model){
		return "new/fileServerManger";
	}
	
	/**
	 * 获取文件服务器管理
	 * @param pageUtil
	 * @return
	 */
	@RequestMapping(value="/getFileServers",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getFileServers(PageUtil pageUtil){
		Map<String, Object> map = new HashMap<String, Object>();
		pageUtil.setPagesize(PAGESIZE);
		pageUtil.setTotalnum(serverService.getTotalRows_servers(pageUtil));
		List<Server> list = serverService.getFileServers(pageUtil);
		map.put("list", list);
		map.put("pageUtil", pageUtil);
		return map;
	}
	
	/**
	 * 视频管理
	 * @return
	 */
	@RequestMapping("/videoManger")
	public String videoManger(Model model){
		return "new/videoManger";
	}

	/**
	 * 视频处理
	 * @param ids
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/startCompute",method = RequestMethod.POST)
	@ResponseBody
	public String startCompute(String ids, Model model)throws Exception{
		
		String[] split = ids.split(",");
		
		for (String i : split) {
			Video video = new Video();
	        Server serverInfo = getServerInfo(Integer.valueOf(i));
	        String ipAddress = serverInfo.getServerip();
	        String fileName = serverInfo.getFilename();
	        String filePath = serverInfo.getFilepath();
			String userName = serverInfo.getUname();
			String passWord = serverInfo.getPwd();
			video.setResultstatus(1);
			serverService.setStatus(video);
			model.addAttribute("rt","ok");
			
			String[] F = {"/bin/sh", "-c", "cd /home/weizzh/AnalyseVideo/; nohup python AnalyseVideo.py -a "+filePath+" -p "+ipAddress+" -u "+userName+" -w "+passWord+" -f "+fileName+" -i "+video.getFileid() +" > /home/weizzh/AnalyseVideo/analys.log &"};
			//CommandUtil.exeCmd(temp);
		}
		
		return "开始分析";
	}
	
	/**
	 * 获取视屏
	 * @param pageUtil
	 * @return
	 */
	@RequestMapping(value="/getVideos",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getVideos(PageUtil pageUtil){
		Map<String, Object> map = new HashMap<String, Object>();
		pageUtil.setPagesize(PAGESIZE);
		pageUtil.setTotalnum(serverService.getTotalRows_video(pageUtil));
		List<Video> list = serverService.getVideos(pageUtil);
		map.put("list", list);
		map.put("pageUtil", pageUtil);
		return map;
	}
	
	/**
	 * 
	 * 上传
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/upload")
	public String upload(HttpServletRequest request) throws IOException{
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				String filename = file.getOriginalFilename();
				if (file != null) {
					InputStream fileIn = file.getInputStream();
					boolean flag = Ftputil.uploadFile("192.168.138.139", 21, "uftp", "admin", ".", filename, fileIn);
				/*	String path = "E:/springUpload" + file.getOriginalFilename();
					file.transferTo(new File(path));*/
				}

			}

		}
		
		return "new/videoList";
	}
	
	/**
	 * 注册页
	 * @return
	 */
	@RequestMapping("/registerManger")
	public String registerManger(){
		return "new/registerManger";
	}
	
	/**
	 * 用户管理
	 * @return
	 */
	@RequestMapping("/accountManger")
	public String accountManger(){
		return "new/accountManger";
	}
	
	public Server getServerInfo(Integer id){
		return serverService.getServerInfo(id);
	}


	/**
	 * 获取用户列表
	 * @return
	 */
	@RequestMapping(value="/getUsers",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> getUsers(PageUtil pageUtil){
		Map<String, Object> map = new HashMap<String, Object>();
		pageUtil.setPagesize(PAGESIZE);
		pageUtil.setTotalnum(serverService.getTotalRows_user(pageUtil));
		List<User> list = serverService.getUsers(pageUtil);
		map.put("list", list);
		map.put("pageUtil", pageUtil);
		return map;
	}




	@RequestMapping("/updateUser")
	@ResponseBody
	public String updateUser(User user){
		serverService.updateUser(user);
		return "1";
	}


	public String checkLogin(HttpServletRequest request, String url){
        try{
            User user = (User) request.getSession().getAttribute("user");
            if(user!=null){
                return url;
            }else{
                return  "error/noLogin_error";
            }
        }catch (Exception e){
            if(e.toString().contains("Null")){
                return "error/noLogin_error";
            }
        }
        return "";
    }

}
